﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using log4net;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using System.Security.Cryptography;
using System.Diagnostics;

namespace PhoneNumberOrder
{
    public partial class MainFrm : Form
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public static MainFrm self = null;
        public delegate void myDelegate(int threadId,object obj);

        //private string historyPhoneFilePath = "";
        private List<NumRuleObject> m_NumRules;
        private Encoding m_Encoding = Encoding.GetEncoding("UTF-8");
        private List<Thread> m_ThreadList = new List<Thread>();
        private Dictionary<string, IList> m_NewPhoneList = new Dictionary<string, IList>();
        private Dictionary<string, IList> m_HistoryPhoneList = new Dictionary<string, IList>();
        private Dictionary<string, bool> m_HistoryListIsDone = new Dictionary<string, bool>();
        private NewPhoneShowFrm m_NewPhoneShowFrm = new NewPhoneShowFrm();

        private bool m_IsScaned = false;//是否已经扫描过
        private bool m_IsScaning = false;//是否正在扫描
        private string m_City = "";
        private string m_CityId = "";
        private string m_PriceRange = "";
        private bool m_IsNoContainFour = true;
        private string m_ScanPhoneFilter = "";
        private int m_ScanThreadCount = -1;
        private string m_Filter = "";
        private string m_RuleFilter = "";
        private bool m_IsNeedRefreshNewPhone = false;
        private DateTime? m_ScanStopTime = null;
        private Dictionary<string, string> mCityList = new Dictionary<string, string>();
        private List<ManualResetEvent> mSetList = new List<ManualResetEvent>();
        private List<string> mShowText = new List<string>();
        //private List<long> mScanPageCountList = new List<long>();
        private List<string> m_LockPhoneList = new List<string>();
        private ReaderWriterLock m_HistoryRwlock = new ReaderWriterLock();
        private List<string[]> m_VerifyCodeList = new List<string[]>();
        private List<List<string[]>> m_AutoVerifyCodeList = new List<List<string[]>>();

        private static object m_LockObj = new object();
        public static bool IsDataOk = true;
        public MainFrm()
        {
            self = this;
            InitializeComponent();
            Sunisoft.IrisSkin.SkinEngine skin = new Sunisoft.IrisSkin.SkinEngine();
            skin.SkinFile = System.Environment.CurrentDirectory + "\\Skins\\MacOS\\" + "MacOS.ssk";
            skin.Active = true;
        }

        public void loadRuleComboBox(ComboBox cb)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("name");

            cb.Items.Clear();
            DataRow newRow = dt.NewRow();
            newRow[0] = "全部";
            newRow[1] = "全部";
            dt.Rows.Add(newRow);
            foreach (NumRuleObject o in m_NumRules)
            {
                if (o.num == "regExp")
                {
                    foreach (string[] item in o.opts)
                    {
                        newRow = dt.NewRow();
                        newRow[0] = item[0];
                        newRow[1] = item[0];
                        dt.Rows.Add(newRow);
                    }
                }
                else
                {
                    newRow = dt.NewRow();
                    newRow[0] = o.name;
                    newRow[1] = o.name;
                    dt.Rows.Add(newRow);
                }
                
            }
            cb.Items.Clear();
            cb.ValueMember = "id";
            cb.DisplayMember = "name";
            cb.DataSource = dt;
        }
        private void InitList()
        {
            m_NumRules = new List<NumRuleObject>();
            m_NumRules.Add(NumRuleObject.create("beautiful", "极品靓号", "juepin@juepin@juepin#jipin@jipin@jipin#jingpin@jingpin@jingpin#tese@tese@tese#shenmi@shenmi@shenmi"));
            m_NumRules.Add(NumRuleObject.create("regExp", "规则号码", @"(\d)((?!\1)\d)((?!\2)\d)(\3{1})$@AA@regExp#(\d)((?!\1)\d)(\2{2})$@AAA@regExp#(\d)(\1{3})$@AAAA@regExp#(\d)(\1{3})(?!\1)\d$@AAAAB@regExp#(\d)(\1{2})(?!\1)\d$@AAAB@regExp#(\d)\1((?!\1)\d)\2$@AABB@regExp#(\d)((?!\1)\d)\1\2$@ABAB@regExp#(\d)((?!\1)\d)\1\2\1$@ABABA@regExp#(\d)((?!\1)\d)\2\1$@ABBA@regExp#(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){2}\d$@ABC@regExp#(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){3}\d$@ABCD@regExp#(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){4}\d$@ABCDE@regExp"));
            m_NumRules.Add(NumRuleObject.create("birthNum", "生日号码", @"1@一月@birthNum#2@二月@birthNum#3@三月@birthNum#4@四月@birthNum#5@五月@birthNum#6@六月@birthNum#7@七月@birthNum#8@八月@birthNum#9@九月@birthNum#10@十月@birthNum#11@十一月@birthNum#12@十二月@birthNum"));
            m_NumRules.Add(NumRuleObject.create("loveNum", "爱情号码", @"1314@一生一世~1314@loveNum#2013@爱你一生~2013@loveNum#3344@生生世世~3344@loveNum#520@我爱你~520@loveNum#5230@我爱上你~5230@loveNum#7758@亲亲我吧~7758@loveNum"));
            m_NumRules.Add(NumRuleObject.create("luckyNum", "吉祥号码", @"168@一路发~168@luckyNum#1818@要发要发~1818@luckyNum#518@我要发~518@luckyNum#666@六六大顺~666@luckyNum#888@发发发~888@luckyNum#99@久久不忘~99@luckyNum"));
            m_NumRules.Add(NumRuleObject.create("constellNum", "星座号码", @"0321-0331,0401-0419@白羊座@constellNum#0823-0831,0901-0922@处女座@constellNum#0420-0430,0501-0520@金牛座@constellNum#0622-0630,0701-0722@巨蟹座@constellNum#1222-1231,0101-0119@魔蝎座@constellNum#1123-1130,1201-1221@射手座@constellNum#0723-0731,0801-0822@狮子座@constellNum#0219-0229,0301-0320@双鱼座@constellNum#0521-0531,0601-0621@双子座@constellNum#0120-0131,0201-0218@水瓶座@constellNum#0923-0930,1001-1023@天秤座@constellNum#1024-1031,1101-1122@天蝎座@constellNum"));
            m_NumRules.Add(NumRuleObject.create("all", "普通号码", ""));

            this.loadRuleComboBox(this.comboBox1);

            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("name");

            string strCity = "531@济南,532@青岛,533@淄博,534@德州,535@烟台,536@潍坊,537@济宁,538@泰安,539@临沂,530@菏泽,543@滨州,546@东营,631@威海,632@枣庄,633@日照,634@莱芜,635@聊城";
            string[] cityList = strCity.Split(new char[] { ','});
            foreach (string city in cityList)
            {
                string[] idNameList = city.Split(new char[] { '@' });
                mCityList.Add(idNameList[0], idNameList[1]);

                DataRow newRow = dt.NewRow();
                newRow[0] = idNameList[0];
                newRow[1] = idNameList[1];
                dt.Rows.Add(newRow);
            }
          
            
            this.comboBox2.Items.Clear();
            this.comboBox2.ValueMember = "id";
            this.comboBox2.DisplayMember = "name";
            this.comboBox2.DataSource = dt;
        }

        private void WaitTheadFinish()
        {
            foreach (ManualResetEvent set in mSetList)
            {
                set.WaitOne();
            }
            //while (true)
            //{
            //    bool bl = true;
            //    foreach (ManualResetEvent set in mSetList)
            //    {
            //        bl = set.WaitOne(1000);
            //        if (!bl)
            //            break;
            //    }

            //    if (bl)
            //        break;
            //}
            mSetList.Clear();

            this.m_WaitingFinishState = "2";
            if (this.InvokeRequired)
            {
                EventHandler d = new EventHandler(btn_Scan_Click);
                this.Invoke(d, new object[] { null, null });
            }
            else
                btn_Scan_Click(null, null);
        }

        private bool m_IsdogOk = false;
        private bool CheckIsRegister()
        {
            if (m_IsdogOk)
                return m_IsdogOk;

            bool isOk = true;
            if (File.Exists(Global.softdogFilePath))
            {
                List<string> input =
                (List<string>)SerializeHelper.Deserialize(Global.softdogFilePath);
                if (RegisterFrm.checkIsSoftDogOk(input))
                {
                    m_IsdogOk = true;  
                }
                else
                {
                    isOk = false;
                }
            }
            else
            {
                isOk = false;
            }

            if (!isOk)
            {
                while (MainFrm.IsDataOk)
                {
                    RegisterFrm frm = new RegisterFrm();
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        m_IsdogOk = true;
                        return true;
                    }
                }

                bool bl = false;
                try
                {
                    bl = DataHelper.Instance.CheckValid(null);
                }
                catch
                {
                    bl = false;
                }

                while (!bl)
                {
                    RegisterFrm frm = new RegisterFrm();
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        m_IsdogOk = true;
                        return true;
                    }
                }
            }

            return true;
        }

        public static string Md5(string input)
        {
            byte[] result = Encoding.UTF8.GetBytes(input);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output);
        }

        private void MainFrm_Load(object sender, EventArgs e)
        {
            //string s = Encryper.Encrypto("62-4B-89-6F-42-25-F5-47-8C-71-9F-9F-11-39-AD-8B");
            this.dateTimePicker1.Value = DateTime.Now;
            this.dateTimePicker1.Checked = false;
            DateTime ti = DateTime.Parse("2013-10-18");
            long l = ti.Ticks;
            comboBox1.SelectedIndex = 0;

            this.InitList();

            //加载预约帐号,和预约信息
            if (File.Exists(Global.userListFilePath))
                Global.userList = (List<string[]>)SerializeHelper.Deserialize(Global.userListFilePath);

            //加载历史锁定号码信息
            List<string[]> lockNumTmpList = new List<string[]>();
            Global.lockNumList = new List<string[]>();
            if (File.Exists(Global.lockNumFilePath))
                lockNumTmpList = (List<string[]>)SerializeHelper.Deserialize(Global.lockNumFilePath);

            string strVerifyCodeDir = Path.Combine(Application.StartupPath, "VerifyCode");
            if (!Directory.Exists(strVerifyCodeDir))
                Directory.CreateDirectory(strVerifyCodeDir);

            DateTime now = DateTime.Now;
            long d = 30 * 60 * 1000;
            foreach (string[] item in lockNumTmpList)
            {
                DateTime tTime = DateTime.Parse(item[2]);
                if (tTime.AddMilliseconds(d) > now)
                {
                    Global.lockNumList.Add(item);
                    this.m_LockPhoneList.Add(item[1]);
                }
            }
            this.refreshNewPhone();


            //处理旧版本中的数据
            if (Global.userList.Count > 0)
            {
                if (Global.userList[0].Length == 3)
                {
                    List<string[]> list = new List<string[]>();
                    foreach (string[] user in Global.userList)
                    {
                        list.Add(new string[] { user[0], user[1], user[2],"0" });
                    }
                    Global.userList = list;
                    SerializeHelper.Serialize(Global.userListFilePath, Global.userList);
                }
            }

            if (File.Exists(Global.orderSuccessListPath))
                Global.orderSuccessList = (List<OrderInfo>)SerializeHelper.Deserialize(Global.orderSuccessListPath);

            this.setScanBtnEnable();
            this.initPhoneList();

            refreshImageCode();

            CheckIsRegister();

            setJinPingNum();

            Thread t = new Thread(new ThreadStart(refreshVerifyCode));
            t.IsBackground = true;
            t.Start();

            Thread t2 = new Thread(new ThreadStart(reLockPhoneNum));
            t2.IsBackground = true;
            t2.Start();

            for (int i = 0; i < 2; i++)
            {
                List<string[]> list = new List<string[]>();
                this.m_AutoVerifyCodeList.Add(list);
                CreateAutoVerifyCodeThread cvct = new CreateAutoVerifyCodeThread();
                cvct.index = i;
                Thread t3 = new Thread(new ThreadStart(cvct.createAutoVerifyCode));
                t3.IsBackground = true;
                t3.Start();
            }
        }

        private void setJinPingNum()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("name");

            DataRow row = dt.NewRow();
            row["id"] = "juepin";
            row["name"] = "绝品靓号(5日、15日、25日)";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "jipin";
            row["name"] = "极品靓号(4日、14日、24日)";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "jingpin";
            row["name"] = "精品靓号(3日、13日、23日)";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "tese";
            row["name"] = "特色靓号(尾数1、2、0日)";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["id"] = "shenmi";
            row["name"] = "神秘靓号(尾数6、7、8、9日)";

            dt.Rows.Add(row);
            this.comboBox3.Items.Clear();
            this.comboBox3.ValueMember = "id";
            this.comboBox3.DisplayMember = "name";
            this.comboBox3.DataSource = dt;
        }

        private string m_WaitingFinishState = "0";
        private void btn_Scan_Click(object sender, EventArgs e)
        {
            if (m_WaitingFinishState == "1")
                return;

            this.m_City = this.comboBox2.SelectedValue.ToString();
            this.m_CityId = this.m_City;

            int iTest = 0, iTest2 = 0, iTmp;
            
            if (this.textBox2.Text == "")
                this.textBox2.Text = "0";
            if (this.textBox1.Text == "")
                this.textBox1.Text = "0";
            if (!int.TryParse(this.textBox2.Text, out iTest))
            {
                MessageBox.Show("预存金额获围必须为整数！");
                return;
            }

            if (!int.TryParse(this.textBox1.Text, out iTest2))
            {
                MessageBox.Show("预存金额获围必须为整数！");
                return;
            }

            if (iTest2 < iTest)
            {
                iTmp = iTest;
                iTest = iTest2;
                iTest2 = iTmp;
            }
            this.m_PriceRange = iTest.ToString() + "-" + iTest2.ToString();
            if (this.m_PriceRange == "0-0")
                this.m_PriceRange = "";

            this.m_ScanThreadCount = -1;
            //if (this.textBox4.Text != "")
            //{
                if (!int.TryParse(this.textBox4.Text, out this.m_ScanThreadCount))
                {
                    MessageBox.Show("扫描线程数参数必须为整数!");
                    return;
                }
            //}

                this.m_IsNoContainFour = this.chkNoFour.Checked;
                this.m_ScanPhoneFilter = this.phoneNumbersCtrl1.GetFilterStr();
                if (this.dateTimePicker1.Checked)
                    m_ScanStopTime = this.dateTimePicker1.Value;
                else
                    m_ScanStopTime = null;

            if (m_WaitingFinishState == "0")
            {
                this.m_IsScaning = !this.m_IsScaning;

                if (!this.m_IsScaning)
                {
                    m_WaitingFinishState = "1";
                    Thread t = new Thread(new ThreadStart(this.WaitTheadFinish));
                    t.IsBackground = true;
                    t.Start();
                    return;
                }
            }
            m_WaitingFinishState = "0";
            this.mShowText.Clear();
            //this.m_LockPhoneList.Clear();
            if (this.m_IsScaning)
            {
                if (this.m_IsScaned){
                    //if (MessageBox.Show("是否清除上次扫描的结果？", "确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    //    this.reSetPhoneList();
                }
                this.AbortThreads();

                Thread t;
                if (this.cbk1.Checked)
                {
                    this.mShowText.Add("");
                    t = new Thread(new ThreadStart(this.thread0));
                    t.IsBackground = true;
                    t.Start();
                    this.m_ThreadList.Add(t);
                    this.mSetList.Add(new ManualResetEvent(false));
                }
                else
                {
                    this.mShowText.Add("1、[极品靓号]不扫描");
                    this.lb1.Text = "1、[极品靓号]不扫描";
                    this.mSetList.Add(new ManualResetEvent(true));
                }

                if (this.cbk2.Checked)
                {
                    this.mShowText.Add("");
                    t = new Thread(new ThreadStart(this.thread1));
                    t.IsBackground = true;
                    t.Start();
                    this.m_ThreadList.Add(t);
                    this.mSetList.Add(new ManualResetEvent(false));
                }
                else
                {
                    this.mShowText.Add("2、[规则号码]不扫描");
                    this.lb2.Text = "2、[规则号码]不扫描";
                    this.mSetList.Add(new ManualResetEvent(true));
                }

                if (this.cbk3.Checked)
                {
                    this.mShowText.Add("");
                    t = new Thread(new ThreadStart(this.thread2));
                    t.IsBackground = true;
                    t.Start();
                    this.m_ThreadList.Add(t);
                    this.mSetList.Add(new ManualResetEvent(false));
                }
                else
                {
                    this.mShowText.Add("3、[生日号码]不扫描");
                    this.lb3.Text = "3、[生日号码]不扫描";
                    this.mSetList.Add(new ManualResetEvent(true));
                }

                if (this.cbk4.Checked)
                {
                    this.mShowText.Add("");
                    t = new Thread(new ThreadStart(this.thread3));
                    t.IsBackground = true;
                    t.Start();
                    this.m_ThreadList.Add(t);
                    this.mSetList.Add(new ManualResetEvent(false));
                }
                else
                {
                    this.mShowText.Add("4、[爱情号码]不扫描");
                    this.lb4.Text = "4、[爱情号码]不扫描";
                    this.mSetList.Add(new ManualResetEvent(true));
                }

                if (this.cbk5.Checked)
                {
                    this.mShowText.Add("");
                    t = new Thread(new ThreadStart(this.thread4));
                    t.IsBackground = true;
                    t.Start();
                    this.m_ThreadList.Add(t);
                    this.mSetList.Add(new ManualResetEvent(false));
                }
                else
                {
                    this.mShowText.Add("5、[吉祥号码]不扫描");
                    this.lb5.Text = "5、[吉祥号码]不扫描";
                    this.mSetList.Add(new ManualResetEvent(true));
                }

                if (this.cbk6.Checked)
                {
                    this.mShowText.Add("");
                    t = new Thread(new ThreadStart(this.thread5));
                    t.IsBackground = true;
                    t.Start();
                    this.m_ThreadList.Add(t);
                    this.mSetList.Add(new ManualResetEvent(false));
                }
                else
                {
                    this.mShowText.Add("6、[星座号码]不扫描");
                    this.lb6.Text = "6、[星座号码]不扫描";
                    this.mSetList.Add(new ManualResetEvent(true));
                }

                if (this.cbk7.Checked)
                {
                    this.mShowText.Add("");
                    t = new Thread(new ThreadStart(this.thread6));
                    t.IsBackground = true;
                    t.Start();
                    this.m_ThreadList.Add(t);
                    this.mSetList.Add(new ManualResetEvent(false));
                }
                else
                {
                    this.mShowText.Add("7、[普通号码]不扫描");
                    this.lb7.Text = "7、[普通号码]不扫描";
                    this.mSetList.Add(new ManualResetEvent(true));
                }

              
                this.btn_Scan.Text = "结束扫描";
                this.lb_Zt.Text = "系统当前状态：正在执行扫描";
                this.comboBox2.Enabled = false;
                this.textBox2.ReadOnly = true;
                this.textBox4.ReadOnly = true;
                this.textBox1.ReadOnly = true;
                //this.checkBox1.Enabled = false;
                //this.checkBox2.Enabled = false;
                this.chkNoFour.Enabled = false;
                this.phoneNumbersCtrl1.SetReadOnly(true);
                this.dateTimePicker1.Enabled = false;
                this.cbk1.Visible = false;
                this.cbk2.Visible = false;
                this.cbk3.Visible = false;
                this.cbk4.Visible = false;
                this.cbk5.Visible = false;
                this.cbk6.Visible = false;
                this.cbk7.Visible = false;

                
                this.m_IsScaned = true;
            }
            else
            {
                this.btn_Scan.Text = "开始扫描";
                this.lb_Zt.Text = "系统当前状态：正在关闭刷新线程";
                //this.AbortThreads();
                this.setScanBtnEnable();
                //WavPlayer.stopPlay();
            }
        }

        private void initPhoneList()
        {
            m_NewPhoneList = new Dictionary<string, IList>();
            m_HistoryPhoneList = new Dictionary<string, IList>();
            m_HistoryListIsDone = new Dictionary<string, bool>();
            foreach (NumRuleObject rule in m_NumRules)
            {
                IList list = ArrayList.Synchronized(new ArrayList());
                m_NewPhoneList.Add(rule.num, list);

                IList list2 = ArrayList.Synchronized(new ArrayList());
                m_HistoryPhoneList.Add(rule.num, list2);

                m_HistoryListIsDone.Add(rule.num, false);
            }
        }

        public void refreshNewPhone()
        {
            if (this.InvokeRequired)
            {
                MethodInvoker d = new MethodInvoker(refreshNewPhone);
                this.Invoke(d);
            }
            else
            {
                this.dataGridView1.Rows.Clear();
                DataGridViewRow row;
                int len = Global.lockNumList.Count;
                for (int i = len - 1; i > -1; i--)
                {
                    string[] item = Global.lockNumList[i];

                    if (m_Filter != "" && item[1].IndexOf(m_Filter) < 0)
                        continue;

                    if (m_RuleFilter != "" && item[0] != m_RuleFilter)
                        continue;
               
                    this.dataGridView1.Rows.Add();
                    row = this.dataGridView1.Rows[this.dataGridView1.RowCount - 1];
                    row.Cells[0].Value = item[0];
                    row.Cells[1].Value = item[1];
                    
                    if (item.Length > 6)
                    {
                        row.Cells[2].Value = item[6];
                        row.Cells[3].Value = item[7];
                    }
                    else
                    {
                        row.Cells[2].Value = "";
                        row.Cells[3].Value = "";
                    }
                    row.Cells[4].Value = item[2];
                    row.Cells[5].Value = item[4];
                    row.Tag = item;
                }
            }
        }

        #region 线程相关函数
        private string m_NewSessionId = "";
        private long m_LastRefreshImageTime = 0;
        private void refreshImageCode()
        {
            try
            {
                this.pictureBox1.Image = null;
                string fileName = Path.Combine(Application.StartupPath, "imgCode.jpg");
                string url = "http://www.sd.10086.cn/emall/image.action?time=" + Guid.NewGuid().ToString();
                WebClient client = new WebClient();
                
                client.DownloadFile(url, fileName);
                this.pictureBox1.Load(fileName);

                this.txtVerifyCode.Text = "";
                this.txtVerifyCode.Focus();

                m_NewSessionId = client.ResponseHeaders["Set-Cookie"];
                m_LastRefreshImageTime = DateTime.Now.Millisecond;
            }
            catch
            {
                
            }
        }

        private void refreshVerifyCode()
        {
            while (true)
            {
                try
                {
                
                    Thread.Sleep(1000 * 60 * 10);

                    List<string[]> list = new List<string[]>();
                    lock (this.m_VerifyCodeList)
                    {
                        foreach (string[] item in this.m_VerifyCodeList)
                        {
                            list.Add(new string[] { item[0], item[1] });
                        }
                    }

                    foreach (string[] item in this.m_VerifyCodeList)
                    {
                        //Thread.Sleep(100);
                        refreshVerifyCode(item[0], item[1]);
                    }
                }
                catch
                {

                }
            }
        }

        private void refreshVerifyCode(string verifyCode,string sessionId)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.NoDelay = true;
            try
            {
                string data = "telNum=18888888888&region=531&code=abcd&vproductId=&continue_url=";
                Uri uri = new Uri("http://www.sd.10086.cn/");
                socket.Connect(uri.Host, uri.Port);
                string strResult = "";
                string strSendInfo = "POST /emall/numAjax/numNewAjax!lockNum.action HTTP/1.1\r\n"
                                    + "Content-Type: application/x-www-form-urlencoded\r\n"
                                    + "Content-Length: " + data.Length.ToString() + "\r\n"
                                    + "Connection: Keep-Alive\r\n"
                                    + "Host: www.sd.10086.cn\r\n"
                                    + "Cookie: " + sessionId + "\r\n\r\n"
                                    + data + "\r\n";
                socket.Send(this.m_Encoding.GetBytes(strSendInfo));
                strResult = this.getSocketReceiveText(socket, "\"returnMsg\":");
            }
            finally
            {
                socket.Close();
            }
        }

        private void reLockPhoneNum()
        {
            while(true)
            {
                try
                {
                    Thread.Sleep(1000 * 5);

                    List<string[]> list = new List<string[]>();
                    lock(Global.lockNumList)
                    {
                        foreach (string[] item in Global.lockNumList)
                        {
                            string[] obj = new string[item.Length];
                            for (int i = 0; i < item.Length; i++ )
                            {
                                obj[i] = item[i];
                            }
                            list.Add(obj);
                        }
                    }

                    foreach (string[] item in list)
                    {
                        if (item[4] == "true" && DateTime.Parse(item[2]).AddMinutes(5) < DateTime.Now 
                            && DateTime.Parse(item[2]).AddMinutes(30) > DateTime.Now)
                        {
                            MainFrm.self.lockNumDelay(item[0], item[1], item[6], item[7], item[8], item[5], item[3], item[9]);
                        }
                    }
                }
                catch (System.Exception e)
                {
                	
                }
            }
        }

        public void createAutoVerifyCode(int index)
        {
            while (true)
            {
                try
                {
                    List<string[]> list = m_AutoVerifyCodeList[index];
                    string[] code = getVerifyCodeText(index);
                    if (code != null)
                    {
                        lock (m_AutoVerifyCodeList)
                        {
                            if (m_AutoVerifyCodeList.Count > 100)
                                m_AutoVerifyCodeList.RemoveAt(0);
                            list.Add(code);
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    log.Debug("验证码破解出错：" + ex.Message);
                }
            }
        }

        private Regex reSpace = new Regex("\\s");
        private Regex reNum = new Regex("[0-9]{4}");

        private string[] getVerifyCodeText(int index)
        {
            string fileName = Path.Combine(Application.StartupPath, @"VerifyCode\imgCode" + index + ".jpg");
            string preProcessFileName = Path.Combine(Application.StartupPath, @"VerifyCode\preImgCode" + index + ".jpg");
            string url = "http://www.sd.10086.cn/emall/image.action?time=" + Guid.NewGuid().ToString();
            WebClient client = new WebClient();
            client.DownloadFile(url, fileName);

            string sessionId = client.ResponseHeaders["Set-Cookie"];

            FileStream fs = null;
            Image img = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                img = Image.FromStream(fs);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
            }

            img = UnCodebase.PreProcess((Bitmap)img);
            img.Save(preProcessFileName);

            using (Process process = new Process())
            {
                string strOutputPath = Path.Combine(Application.StartupPath, @"VerifyCode\imgText" + index);
                process.StartInfo.FileName = "tesseract.exe";
                process.StartInfo.Arguments = preProcessFileName + " " + strOutputPath;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;
                //process.StartInfo.WorkingDirectory = Application.StartupPath;
                process.Start();
                process.WaitForExit();
                
                try
                {
                    fs = new FileStream(strOutputPath + ".txt", FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    string txt = sr.ReadToEnd();
                    txt = reSpace.Replace(txt, "");

                    if (reNum.IsMatch(txt))
                        return new string[] { txt, sessionId };
                    else
                        return null;
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                        fs = null;
                    }
                }

            }
        }

        
        private void thread0()
        {
            scanStart(1, m_NumRules[0]);
        }

        private void thread1()
        {
            scanStart(2, m_NumRules[1]);
        }

        private void thread2()
        {
            scanStart(3, m_NumRules[2]);
        }

        private void thread3()
        {
            scanStart(4, m_NumRules[3]);
        }

        private void thread4()
        {
            scanStart(5, m_NumRules[4]);
        }
        private void thread5()
        {
            scanStart(6, m_NumRules[5]);
        }
        private void thread6()
        {
            scanStart(7,m_NumRules[6]);
        }

        private void scanStart(int threadId,NumRuleObject rule)
        {
            try
            {
                string strThreadName = rule.name;
                this.m_HistoryListIsDone[rule.num] = false;
                strThreadName = threadId.ToString() + "、[" + strThreadName + "]:";
                long scanCount = 1;
                long pre, now;
                TimeSpan sp = new TimeSpan();
                string strMsg, strUseTime;
                int scanTheadCount = 1;
                List<ManualResetEvent> setList = new List<ManualResetEvent>();
                while (true)
                {
                    pre = DateTime.Now.Ticks;
                    strMsg = string.Format("{0}第{1}轮", strThreadName, scanCount);
                    strUseTime = "";
                    if (scanCount > 1)
                    {
                        strUseTime = string.Format(",上轮用时:{0}时{1}分{2}秒", sp.Hours, sp.Minutes, sp.Seconds);
                    }

                    string strInfo = strMsg + strUseTime;
                    this.showThreadInfo(threadId, strInfo);

                    IList newPhoneList = this.m_NewPhoneList[rule.num];
                    IList historyPhoneList = this.m_HistoryPhoneList[rule.num];
                    bool isNeedHistory = !this.m_HistoryListIsDone[rule.num];
                    if (isNeedHistory)
                        historyPhoneList.Clear();


                    scanTheadCount = m_ScanThreadCount;
                    if (rule.opts.Count < scanTheadCount)
                        scanTheadCount = rule.opts.Count;

                    if (scanTheadCount < 1)
                        scanTheadCount = 1;

                    if (scanTheadCount > 0)
                    {
                        LockScanThreadObject lockObj = new LockScanThreadObject();
                        for (int i = 0; i < scanTheadCount; i++)
                        {
                            ManualResetEvent set = new ManualResetEvent(false);
                            setList.Add(set);

                            ScanThead scanThead = new ScanThead();
                            scanThead.set = set;
                            scanThead.lockObj = lockObj;
                            scanThead.isNeedHistory = isNeedHistory;
                            scanThead.ruleObject = rule;
                            scanThead.threadId = threadId;
                            scanThead.strMsg = strMsg;
                            scanThead.strUseTime = strUseTime;

                            Thread t = new Thread(new ThreadStart(scanThead.Run));
                            t.IsBackground = true;
                            t.Start();
                        }
                    }

                    foreach (ManualResetEvent set in setList)
                    {
                        set.WaitOne();
                    }

                    setList.Clear();

                    if (isNeedHistory)
                        this.m_HistoryListIsDone[rule.num] = true;

                    now = DateTime.Now.Ticks - pre;
                    sp = new TimeSpan(now);
                    scanCount++;


                    if (checkIsScanStop())
                        break;

                    Thread.Sleep(100);
                }
            }
            catch
            {
            }
            finally
            {
                this.mSetList[threadId - 1].Set();
            }
        }

        public void scanThead(ManualResetEvent set, LockScanThreadObject lockObj, bool isNeedHistory, NumRuleObject rule, int threadId, string strMsg, string strUseTime)
        {
            try
            {
                bool isPrePageOk = true;
                List<PhoneOrder> tmpPagePhoneList;
                string strTmp;
                IList newPhoneList = this.m_NewPhoneList[rule.num];
                IList historyPhoneList = this.m_HistoryPhoneList[rule.num];
                int index = -1;
                while (true)
                {
                    try
                    {
                        if (checkIsScanStop())
                            break;

                        Thread.Sleep(100);

                        if (isPrePageOk)
                            index = lockObj.Add();

                        if (rule.opts.Count > 0 && index >= rule.opts.Count)
                            break;

                        string ruleId = "";
                        string ruleParam = "";
                        if(rule.opts.Count > 0)
                        {
                            ruleId = rule.num;
                            ruleParam = rule.opts[index][1];
                        }
                        strTmp = this.getPageStr(ruleId, ruleParam);
                        tmpPagePhoneList = this.dealPagePhoneInfo(strTmp, rule.num, ruleParam);
                        checkIsNewPhone(rule.num, tmpPagePhoneList, historyPhoneList, newPhoneList, isNeedHistory);
                        isPrePageOk = true;
                    }
                    catch(Exception ex)
                    {
                        isPrePageOk = false;
                        if (ex is NetworkException)
                            log.Debug(string.Format("{0}、[{1}]，扫描时出错：{2},{3}", threadId, rule.name, ex.Message, ex.StackTrace));
                        else
                            log.Debug(string.Format("{0}、[{1}]，扫描时出错：{2},{3}", threadId, rule.name, ex.Message, ex.StackTrace));
                    }
                }

                log.Debug(string.Format("{0}、[{1}]线程结束**************", threadId, rule.name));
            }
            finally
            {
                set.Set();
            }
        }

        private void checkIsNewPhone(string phoneRule,List<PhoneOrder> pagePhoneList, IList historyPhoneList, IList newPhoneList, bool isHistory)
        {
                for (int i = pagePhoneList.Count - 1; i > -1; i-- )
                {
                    PhoneOrder phone = pagePhoneList[i];
                    bool isNew = true;
                    //if (newPhoneList.Count > 20)
                    //    isNew = false;
                    m_HistoryRwlock.AcquireReaderLock(Timeout.Infinite);
                    try
                    {
                        foreach (PhoneOrder obj in historyPhoneList)
                        {
                            if (obj.m_Num == phone.m_Num)
                            {
                                isNew = false;
                                break;
                            }
                        }
                    }
                    finally
                    {

                        m_HistoryRwlock.ReleaseReaderLock();
                    }

                    if (phone.m_PrestoreMoney.EndsWith(".0"))
                        phone.m_PrestoreMoney = phone.m_PrestoreMoney.Replace(".0", "");

                    if (phone.m_BaseFeeMoney.EndsWith(".0"))
                        phone.m_BaseFeeMoney = phone.m_BaseFeeMoney.Replace(".0", "");

                    bool isNeedLock = false;
                    lock (Global.needLockNumList)
                    {
                        foreach (string[] item in Global.needLockNumList)
                        {
                            if (item[1] == phone.m_Num)
                            {
                                isNeedLock = true;
                                //启用了告警提醒b
                                if (item[2] == "1")
                                    playVoice();
                                break;
                            }
                        }
                    }

                    if (isNeedLock)
                        this.lockNum(phone.m_RuleParam, phone.m_Num, phone.m_PrestoreMoney, phone.m_BaseFeeMoney, this.m_CityId);

                    if (isNew)
                    {
                        m_HistoryRwlock.AcquireWriterLock(Timeout.Infinite);
                        try
                        {
                            historyPhoneList.Add(phone);
                        }
                        finally
                        {
                            m_HistoryRwlock.ReleaseWriterLock();
                        }

                        if (phone.m_RuleId == "beautiful" && !isNeedLock)
                        {
                            this.lockNum(phone.m_RuleParam, phone.m_Num, phone.m_PrestoreMoney, phone.m_BaseFeeMoney, this.m_CityId);
                            return;
                        }

                        if (!isHistory)
                        {
                            if (!isNeedLock)
                                this.lockNum(phone.m_RuleParam, phone.m_Num, phone.m_PrestoreMoney, phone.m_BaseFeeMoney, this.m_CityId);
                        }
                    }
                    else
                    {
                        if (phone.m_RuleId == "beautiful" && !isNeedLock)
                        {
                            this.lockNum(phone.m_RuleParam, phone.m_Num, phone.m_PrestoreMoney, phone.m_BaseFeeMoney, this.m_CityId);
                            return;
                        }

                        if (!isHistory && !isNeedLock)
                        {
                            if (this.m_LockPhoneList.Contains(phone.m_Num))
                                this.lockNum(phone.m_RuleParam, phone.m_Num, phone.m_PrestoreMoney, phone.m_BaseFeeMoney, this.m_CityId);
                        }
                    }
                }
        }

        private void showThreadInfo(int threadId,object obj)
        {
            if (!this.m_IsScaning)
                return;

            this.mShowText[threadId - 1] = obj.ToString();
            return;
        }

        private void setScanBtnEnable()
        {
            this.m_IsScaning = false;
            this.btn_Scan.Text = "开始扫描";
            this.lb_Zt.Text = "系统当前状态：空闲";
            this.lb1.Text = "";
            this.lb2.Text = "";
            this.lb3.Text = "";
            this.lb4.Text = "";
            this.lb5.Text = "";
            this.lb6.Text = "";
            this.lb7.Text = "";
            this.comboBox2.Enabled = true;
            this.textBox2.ReadOnly = false;
            this.textBox4.ReadOnly = false;
            this.textBox1.ReadOnly = false;

            //this.checkBox1.Enabled = true;
            //this.checkBox2.Enabled = true;

            this.chkNoFour.Enabled = true;
            this.phoneNumbersCtrl1.SetReadOnly(false);
            this.dateTimePicker1.Enabled = true;
            this.cbk1.Visible = true;
            this.cbk2.Visible = true;
            this.cbk3.Visible = true;
            this.cbk4.Visible = true;
            this.cbk5.Visible = true;
            this.cbk6.Visible = true;
            this.cbk7.Visible = true;
        }

        private void AbortThreads()
        {
            //foreach (Thread t in m_ThreadList)
            //{
            //    if (t != null)
            //    {
            //        t.Abort();
            //        //t = null;
            //    }
            //}
            m_ThreadList.Clear();
        }

        #endregion

        #region Socket处理相关函数
        private string getPageStr(string numRuleId,string param)
        {
            if (!this.m_IsScaning)
                return "";

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.NoDelay = true;
            try
            {
                if (numRuleId != "beautiful")
                {
                    string data = "/emall/numShowNewAjax.action?beginNum=&endNumType=-1&endNumLen=-1&endNumStart=&endNumEnd=&endNums=-1&selfDefType=&reloadRecNum=false&pSort=1";
                    data += "&region=" + this.m_CityId;
                    data += "&preFee=" + this.m_PriceRange;


                    data += "&numRuleId=";
                    if (!string.IsNullOrEmpty(numRuleId) && numRuleId != "All")
                        data += numRuleId;

                    data += "&notFour=";
                    if (this.m_IsNoContainFour)
                        data += "&&notFour=yes";

                    if (!string.IsNullOrEmpty(this.m_ScanPhoneFilter))
                    {
                        data += "&selfDefNum=" + this.m_ScanPhoneFilter + "&selfDefFlag=sefDefQry";
                    }
                    else
                    {
                        data += "&selfDefNum=***********&selfDefFlag=";
                    }

                    if (string.IsNullOrEmpty(numRuleId))
                    {
                        data += "&highQryRule=&highQryType=";
                    }
                    else
                    {
                        data += "&highQryRule=" + param + "&highQryType=" + numRuleId;
                    }

                    Uri uri = new Uri("http://www.sd.10086.cn/");
                    socket.Connect(uri.Host, uri.Port);
                    string strResult = "";
                    string strSendInfo = "POST " + data + " HTTP/1.1\r\n"
                                        + "Content-Type: application/x-www-form-urlencoded\r\n"
                                        + "Content-Length: 0\r\n"
                                        + "Connection: Keep-Alive\r\n"
                                        + "Host: www.sd.10086.cn\r\n\r\n";
                    //+ "Cookie: JSESSIONID=0000p8--C9zGDYo47144DHgMCbl:18s0atvei;\r\n\r\n";
                    socket.Send(this.m_Encoding.GetBytes(strSendInfo));
                    strResult = this.getSocketReceiveText(socket, "\"returnMsg\"");
                    return strResult;
                }
                else
                {
                    string data = string.Format("scenseFlag={0}&region={1}&continue_url=",param,this.m_CityId);

                    Uri uri = new Uri("http://www.sd.10086.cn/");
                    socket.Connect(uri.Host, uri.Port);
                    string strResult = "";
                    string strSendInfo = "POST /emall/activity/queryFlashSaleNum.action HTTP/1.1\r\n"
                                        + "Content-Type: application/x-www-form-urlencoded\r\n"
                                        + "Content-Length: " +data.Length+ "\r\n"
                                        + "Connection: Keep-Alive\r\n"
                                        + "Host: www.sd.10086.cn\r\n\r\n"
                                        + data + "\r\n";
                    socket.Send(this.m_Encoding.GetBytes(strSendInfo));
                    strResult = this.getSocketReceiveText(socket, new string[] { "]}", "</html>" });
                    return strResult;
                }
            }
            finally
            {
                socket.Close();
            }
        }

        private List<PhoneOrder> dealPagePhoneInfo(string recText,string ruleId,string ruleParam)
        {
            NumRuleObject rObj = this.getRuleObjectById(ruleId);
            if(ruleId != "regExp")
            {
                ruleParam = rObj.name;
            }
            else
            {
                ruleParam = this.getRuleParamNameBy(rObj, ruleParam);
            }

            List<PhoneOrder> list = new List<PhoneOrder>();
            if (ruleId != "beautiful")
            {
                string strPattern = "\\s*\"newShowNums\"\\s*:\\s*\\[([^\\]]+)\\]";
                Regex reg = new Regex(strPattern, RegexOptions.Multiline);

                strPattern = "";
                Match ma = reg.Match(recText);
                if (ma.Success)
                {
                    strPattern = "\"minCost\":\"([^\"]+)\"[^\\}]*\"preFee\":\"([^\"]+)\"[^\\}]*\"telNum\":\"([^\"]+)\"[^\\}]*\\}";
                    Regex reg2 = new Regex(strPattern, RegexOptions.Multiline);
                    Match ma2 = reg2.Match(ma.Value);

                    while (ma2.Success)
                    {
                        PhoneOrder phone = new PhoneOrder();
                        phone.m_Num = ma2.Groups[3].Value;
                        phone.m_PrestoreMoney = ma2.Groups[2].Value;
                        phone.m_BaseFeeMoney = ma2.Groups[1].Value;
                        phone.m_CityId = this.m_CityId;
                        phone.m_RuleId = ruleId;
                        phone.m_RuleParam = ruleParam;

                        list.Add(phone);

                        ma2 = ma2.NextMatch();
                    }
                }
            }
            else
            {
                string strPattern = "\\s*\"numList\"\\s*:\\s*\\[([^\\]]+)\\]";
                Regex reg = new Regex(strPattern, RegexOptions.Multiline);

                //strPattern = "\"minCost\":\"([^\"]+)\"[^\\}]*\"preFee\":\"([^\"]+)\"[^\\}]*\"status\":\"0\"[^\\}]*\"telNum\":\"([^\"]+)\"[^\\}]*\\}";
                //Regex reg2 = new Regex(strPattern, RegexOptions.Multiline);

                strPattern = "\"invStatus\":\"USABLE\"[^\\}]*\"minCost\":\"([^\"]+)\"[^\\}]*\"preFee\":\"([^\"]+)\"[^\\}]*\"status\":\"1\"[^\\}]*\"telNum\":\"([^\"]+)\"[^\\}]*\\}";
                Regex reg3 = new Regex(strPattern, RegexOptions.Multiline);
                Match ma = reg.Match(recText);
                if (ma.Success)
                {
                    
                    //Match ma2 = reg2.Match(ma.Value);
                    //if (ma2.Success)
                    //{
                    //    while (ma2.Success)
                    //    {
                    //        PhoneOrder phone = new PhoneOrder();
                    //        phone.m_Num = ma2.Groups[3].Value;
                    //        phone.m_PrestoreMoney = ma2.Groups[2].Value;
                    //        phone.m_BaseFeeMoney = ma2.Groups[1].Value;
                    //        phone.m_CityId = "536";
                    //        phone.m_RuleId = ruleId;
                    //        phone.m_RuleParam = ruleParam;

                    //        list.Add(phone);

                    //        ma2 = ma2.NextMatch();
                    //    }
                    //    return list;
                    //}

                    Match ma3 = reg3.Match(ma.Value);
                    if (ma3.Success)
                    {
                        while (ma3.Success)
                        {
                            PhoneOrder phone = new PhoneOrder();
                            phone.m_Num = ma3.Groups[3].Value;
                            phone.m_PrestoreMoney = ma3.Groups[2].Value;
                            phone.m_BaseFeeMoney = ma3.Groups[1].Value;
                            phone.m_CityId = "536";
                            phone.m_RuleId = ruleId;
                            phone.m_RuleParam = ruleParam;

                            list.Add(phone);

                            ma3 = ma3.NextMatch();
                        }
                        return list;
                    }

                }
            }
            return list;
        }

        private NumRuleObject getRuleObjectById(string ruleId)
        {
            foreach (NumRuleObject o in m_NumRules)
            {
                if(o.num == ruleId)
                {
                    return o;
                }
            }
            
            return null;
        }

        private string getRuleParamNameBy(NumRuleObject o,string ruleParamId)
        {
            foreach (string[] item in o.opts)
            {
                if(ruleParamId == item[1])
                {
                    return item[0];
                }
            }

            return "";
        }

        public string getSocketReceiveText(Socket socket, string strEndTag)
        {
            string strResult = "";
            StringBuilder sb = new StringBuilder();
            socket.ReceiveTimeout = 5 * 1000;//5秒阻塞
            byte[] receivedBytes = new byte[1024 * 1000];
            try
            {
                int receiveCount = 0;
                int totelCount = 0;
                while (true)
                {
                    receiveCount = socket.Receive(receivedBytes, totelCount, receivedBytes.Length - totelCount, SocketFlags.None);
                    totelCount += receiveCount;
                    strResult = this.m_Encoding.GetString(receivedBytes);
                    if (strResult.Contains(strEndTag))
                    {
                        string strPattern = "\r\n[0-9a-f]{1,}\r\n";
                        Regex reg = new Regex(strPattern, RegexOptions.IgnoreCase);
                        strResult = reg.Replace(strResult, "");
                        break;
                    }
                    if (receiveCount == 0)
                        throw new Exception("连接已经连开！");
                }
            }
            catch (Exception ex)
            {
                throw new NetworkException("没能接收到服务器正常数据包！可能与服务器会话丢失，或者服务器不正常！",ex);
            }
            finally
            {
                socket.Close();
            }

            return strResult;
        }

        public string getSocketReceiveText(Socket socket, string[] strEndTag)
        {
            string strResult = "";
            StringBuilder sb = new StringBuilder();
            socket.ReceiveTimeout = 2 * 1000;//5秒阻塞
            byte[] receivedBytes = new byte[1024 * 100];
            try
            {
                int receiveCount = 0;
                int totelCount = 0;
                while (true)
                {
                    receiveCount = socket.Receive(receivedBytes, totelCount, receivedBytes.Length - totelCount, SocketFlags.None);
                    totelCount += receiveCount;
                    strResult = this.m_Encoding.GetString(receivedBytes);
                    
                    if (!strResult.Contains("HTTP/1.1 200 OK"))
                        throw new ApplicationException("没能接收到服务器正常数据包！可能与服务器会话丢失，或者服务器不正常！");

                    bool isContainStr = false;
                    foreach (string str in strEndTag)
                    {
                        if (strResult.Contains(str))
                        {
                            isContainStr = true;
                            break;
                        }
                    }

                    if (isContainStr)
                    {
                        string strPattern = "\r\n[0-9a-f]{1,}\r\n";
                        Regex reg = new Regex(strPattern, RegexOptions.IgnoreCase);
                        strResult = reg.Replace(strResult, "");
                        break;
                    }
                    if (receiveCount == 0)
                        throw new Exception("连接已经连开！");
                }
            }
            catch (Exception ex)
            {
                throw new NetworkException("没能接收到服务器正常数据包！可能与服务器会话丢失，或者服务器不正常！", ex);
            }
            finally
            {
                socket.Close();
            }

            return strResult;
        }

        public string getSocketReceiveText(Socket socket, string[] strEndTag,int bufferLength)
        {
            bufferLength = 1024 * 100;
            string strResult = "";
            StringBuilder sb = new StringBuilder();
            socket.ReceiveTimeout = 1 * 500;//5秒阻塞
            byte[] receivedBytes = new byte[bufferLength];
            try
            {
                int receiveCount = 0;
                int totelCount = 0;
                while (true)
                {
                    receiveCount = socket.Receive(receivedBytes, totelCount, receivedBytes.Length - totelCount, SocketFlags.None);
                    totelCount += receiveCount;
                    strResult = this.m_Encoding.GetString(receivedBytes);

                    if (!strResult.Contains("HTTP/1.1 200 OK"))
                        throw new ApplicationException("没能接收到服务器正常数据包！可能与服务器会话丢失，或者服务器不正常！");

                    bool isContainStr = false;
                    foreach (string str in strEndTag)
                    {
                        if (strResult.Contains(str))
                        {
                            isContainStr = true;
                            break;
                        }
                    }

                    if (isContainStr)
                    {
                        string strPattern = "\r\n[0-9a-f]{1,}\r\n";
                        Regex reg = new Regex(strPattern, RegexOptions.IgnoreCase);
                        strResult = reg.Replace(strResult, "");
                        break;
                    }
                    if (receiveCount == 0)
                        throw new Exception("连接已经连开！");
                }
            }
            catch (Exception ex)
            {
                throw new NetworkException("没能接收到服务器正常数据包！可能与服务器会话丢失，或者服务器不正常！", ex);
            }
            finally
            {
                socket.Close();
            }

            return strResult;
        }

        private string getInputVal(string str, string keyName)
        {
            string strResult = "";
            Regex regex = new Regex("name\\s*=\\s*\"" + keyName + "\"\\s*value\\s*=\\s*\"(\\w*)\"", RegexOptions.IgnoreCase);
            Match ma = regex.Match(str);
            if (ma.Success)
                strResult = ma.Groups[1].Value;
            return strResult;
        }

        private string getJsonVal(string str, string keyName)
        {
            string strResult = "";
            Regex regex = new Regex("\\s*\"" + keyName + "\"\\s*:\\s*\"([^\"]*)\"", RegexOptions.IgnoreCase);
            Match ma = regex.Match(str);
            if (ma.Success)
                strResult = ma.Groups[1].Value;
            return strResult;
        }
        #endregion

        #region 播放声音相关函数
        private void playVoice()
        {
            WavPlayer.Play(Path.Combine(Application.StartupPath, "Sound.wav"));
        }

        private void stopVoice()
        {
            WavPlayer.stopPlay();
        }
        #endregion

        private void pl_Content_SizeChanged(object sender, EventArgs e)
        {
            //this.refreshNewPhone();
        }

        private void btn_Search_Click(object sender, EventArgs e)
        {
            this.m_Filter = this.txt_Search.Text;
            if (this.comboBox1.SelectedIndex > 0)
                this.m_RuleFilter = this.comboBox1.SelectedValue.ToString();
            else
                this.m_RuleFilter = "";
            this.refreshNewPhone();

            string strFilterInfo = "";
            if (this.m_RuleFilter != "")
                strFilterInfo = "规则--" + this.m_RuleFilter;

            if (this.m_Filter != "")
                strFilterInfo += " 号码--" + this.m_Filter;
            else
                this.label5.Text = "";

            if(strFilterInfo != "")
                this.label5.Text = "过滤：" + strFilterInfo;
            else
                this.label5.Text = "";
        }

        private void btn_Reset_Click(object sender, EventArgs e)
        {
            this.comboBox1.SelectedIndex = 0;
            this.txt_Search.Text = "";
            this.m_Filter = "";
            this.label5.Text = "";
            this.refreshNewPhone();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.stopVoice();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.playVoice();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            OrderUserManageFrm frm = new OrderUserManageFrm();
            frm.ShowDialog();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            OrderInfoSearchFrm frm = new OrderInfoSearchFrm();
            frm.ShowDialog();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            HistoryPhoneNumSearchFrm frm = new HistoryPhoneNumSearchFrm();
            frm.ShowDialog();
        }

        public Dictionary<string, IList> getHistoryPhoneList()
        {
            return m_HistoryPhoneList;
        }


        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
            object[] datas = (object[])row.Tag;
            IList list = (IList)datas[0];
            PhoneOrder phone = (PhoneOrder)datas[1];
            if (e.ColumnIndex == 4)
            {
                if (phone.m_Order == null)
                {
                    OrderFrm frm = new OrderFrm();
                    frm.m_Phone = phone;
                    frm.ShowDialog();
                }
                else
                {
                    OrderSuccessFrm frm = new OrderSuccessFrm();
                    frm.Text = "查看预约信息";
                    frm.info = phone.m_Order.ToString();
                    frm.ShowDialog();
                }
            }
            else if (e.ColumnIndex == 5)
            {
                if (MessageBox.Show("确定要移除该号码吗？", "确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    list.Remove(phone);
                    this.dataGridView1.Rows.RemoveAt(e.RowIndex);
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.m_IsScaning)
            {
                if (m_ScanStopTime != null && DateTime.Now.CompareTo(m_ScanStopTime) > 0)
                    this.btn_Scan_Click(null, null);
            }

            if (m_IsNeedRefreshNewPhone)
            {
                m_IsNeedRefreshNewPhone = false;
                this.refreshNewPhone();
            }

            this.lbVerifyCodeNum.Text = "当前可用验证码（" + m_VerifyCodeList.Count + "）个";
        }

        private void comboBox2_TextChanged(object sender, EventArgs e)
        {
            m_HistoryPhoneList = new Dictionary<string, IList>();
            m_HistoryListIsDone = new Dictionary<string, bool>();
            foreach (NumRuleObject rule in m_NumRules)
            {
                IList list2 = ArrayList.Synchronized(new ArrayList());
                m_HistoryPhoneList.Add(rule.num, list2);

                m_HistoryListIsDone.Add(rule.num, false);
            }
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            ProductCarFrm frm = new ProductCarFrm();
            frm.ShowDialog();
        }

        public string[] lockNum(string phoneRule, string phoneNum,string strPrePrice, string strBaseFee, string cityId)
        {
            string data, re, strSendInfo;
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.NoDelay = true;
            try
            {
                string[] verifyCode = this.getVerifyCode();

                Regex reg = new Regex("JSESSIONID=([^;]+);", RegexOptions.Multiline);
                Match ma = reg.Match(verifyCode[1]);
                string svrSession = ma.Groups[1].ToString();

                data = string.Format("telNum={0}&region={1}&code={2}&vproductId=&continue_url=http%253A%252F%252Fwww.sd.10086.cn%252Femall%252Fnumshow%252FnumNewShow!showCacheList.action", phoneNum, cityId, verifyCode[0]);
                Uri uri = new Uri("http://www.sd.10086.cn/");
                socket.Connect(uri.Host, uri.Port);

                strSendInfo = "POST /emall/numAjax/numNewAjax!lockNum.action HTTP/1.1\r\n"
                                   + "Referer: http://www.sd.10086.cn/emall/numshow/numNewShow!showCacheList.action\r\n"
                                   + "Content-Type: application/x-www-form-urlencoded\r\n"
                                   + "Content-Length: " + data.Length.ToString() + "\r\n"
                                   + "Connection: Keep-Alive\r\n"
                                   + "Host: www.sd.10086.cn\r\n"
                                   + "Cookie: " + verifyCode[1] + "\r\n\r\n"
                                   + data + "\r\n";
                socket.Send(this.m_Encoding.GetBytes(strSendInfo));

                //Thread.Sleep(10);
                re = this.getSocketReceiveText(socket, new string[] { "\"returnMsg\":", "</html>" });
                string vproductId = this.getJsonVal(re, "vproductId");
                string returnMsg = this.getJsonVal(re,"returnMsg");
                string reBool = "false";
                if (returnMsg == "1")
                {
                    if (!string.IsNullOrEmpty(vproductId))
                    {
                        reBool = "true";
                    }
                    else
                    {
                        log.Debug("锁定号码时出错，vproductId为空！");
                    }
                }
                else if(returnMsg == "2")
                {
                    log.Debug("锁定号码时出错，验证码错误！");
                    lockNum(phoneRule, phoneNum, strPrePrice, strBaseFee, cityId);
                    return null;
                }
                else
                {
                    log.Debug("锁定号码时出错，错误号：" + returnMsg);
                }
                

                string temp_car = vproductId;
                addLockNum(phoneRule, phoneNum, temp_car, reBool, svrSession, strPrePrice, strBaseFee, cityId, verifyCode[0]);
                return new string[] { temp_car, svrSession, reBool, verifyCode[0]};
            }
            catch(Exception ex)
            {
                log.Debug("锁定号码时出错：" + ex.Message);
                return null;
            }
            finally
            {
                socket.Close();
            }
        }

        public void lockNumDelay(string phoneRule, string phoneNum, string strPrePrice, string strBaseFee, string cityId, string svrSession, string vproductId, string code)
        {
            string  re, strSendInfo;
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.NoDelay = true;
            try
            {
                string sessionId = string.Format("Cookie:JSESSIONID={0};", svrSession);
                Uri uri = new Uri("http://www.sd.10086.cn/");
                socket.Connect(uri.Host, uri.Port);

                string url = "/emall/numshow/numAjax!delay.action?paramMap.vprodId=" + vproductId + "&d=" + DateTime.Now.Millisecond + "&continue_url=";
                strSendInfo = "POST " + url + " HTTP/1.1\r\n"
                                   + "Content-Length: 0\r\n"
                                   + "Content-Type: application/x-www-form-urlencoded\r\n"
                                   + "Connection: Keep-Alive\r\n"
                                   + "Host: www.sd.10086.cn\r\n"
                                   + "Cookie: " + sessionId + "\r\n\r\n";
                socket.Send(this.m_Encoding.GetBytes(strSendInfo));

                //Thread.Sleep(10);
                re = this.getSocketReceiveText(socket, new string[] { "HTTP/1.1 200"});

                string reBool = "true";
                string temp_car = vproductId;
                addLockNum(phoneRule, phoneNum, temp_car, reBool, svrSession, strPrePrice, strBaseFee, cityId, code);
            }
            catch (Exception ex)
            {
                log.Debug("延时锁定时出错：" + ex.Message);
            }
            finally
            {
                socket.Close();
            }
        }

        public void showProductCar(string vproductId, string svrSession, string phoneNum, string cityId, string code)
        {
            svrSession = svrSession + ";path=/;expires=" + DateTime.Now.AddHours(1).ToString("R");
            if (!WebCookieToken.InternetSetCookie("http://www.sd.10086.cn", "JSESSIONID", svrSession))
            {
                MessageBox.Show("写入购物车Cookie时出错，错误码:" + WebCookieToken.GetLastError().ToString());
                return;
            }

            string temp_car = vproductId + ";path=/;expires=" + DateTime.Now.AddHours(1).ToString("R");
            if (!WebCookieToken.InternetSetCookie("http://www.sd.10086.cn", "vproductId", temp_car))
            {
                MessageBox.Show("写入购物车Cookie时出错，错误码:" + WebCookieToken.GetLastError().ToString());
                return;
            }

            string cityName = this.urlEncod(this.mCityList[cityId]);
            string url = string.Format("http://www.sd.10086.cn/emall/numshow/productTempChoice.action?"
                                    + "telNum={0}&vproductId={1}&cproductId=&tempId=&regions={2}&code={3}&regionName={4}&channel=&isJt="
                                    , phoneNum, vproductId, code, cityId, cityName);
            System.Diagnostics.Process.Start("iexplore.exe", url);
        }

        public void addLockNum(string phoneRule, string phoneNum, string temp_car, string lockstate, string svrSession, string strPrePrice, string strBaseFee, string cityId, string code)
        {
            lock (m_LockObj)
            {
                string[] item = null;
                foreach (string[] it in Global.lockNumList)
                {
                    if (it[1] == phoneNum)
                    {
                        item = it;
                        break;
                    }
                }

                if (item != null)
                {
                    if (lockstate != "true")
                        return;
                    Global.lockNumList.Remove(item);
                }

                lock (this.m_LockPhoneList)
                {
                    if (!this.m_LockPhoneList.Contains(phoneNum))
                        this.m_LockPhoneList.Add(phoneNum);
                }
                Global.lockNumList.Add(new string[] { phoneRule, phoneNum, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), temp_car, lockstate, svrSession, strPrePrice, strBaseFee, cityId , code});
                m_IsNeedRefreshNewPhone = true;
            }
        }

        public void deleteLockNum()
        {
            DataGridViewRow row = this.dataGridView1.CurrentRow;
            if (row == null)
                return;

            lock (m_LockObj)
            {
                //加载历史锁定号码信息
                List<string[]> lockNumTmpList = new List<string[]>();

                for(int i=0; i < Global.lockNumList.Count; i++)
                {
                    if(Global.lockNumList[i][1] == row.Cells[1].Value.ToString())
                    {
                        Global.lockNumList.Remove(Global.lockNumList[i]);
                        break;
                    }
                }

            }
        }

        private void MainFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //if (this.m_IsScaning)
            //{
            //    MessageBox.Show("请先停止扫描再关闭！","提示");
            //    e.Cancel = true;
            //}
        }

        private void MainFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            SerializeHelper.Serialize(Global.lockNumFilePath, Global.lockNumList);

            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if(!this.m_IsScaning)
                return;

            if (this.InvokeRequired)
            {
                EventHandler d = new EventHandler(timer2_Tick);
                this.Invoke(d, new object[] { null, null });
            }
            else
            {
                lb1.Text = this.mShowText[0];
                lb2.Text = this.mShowText[1];
                lb3.Text = this.mShowText[2];
                lb4.Text = this.mShowText[3];
                lb5.Text = this.mShowText[4];
                lb6.Text = this.mShowText[5];
                lb7.Text = this.mShowText[6];
            }
        }

        public static void RenderToExcel(DataTable table)
        {
            string filePath = Path.Combine(Application.StartupPath, "ExportFile.xls");
            Stream ms = null;
            try
            {
                ms = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
                IWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();
                sheet.SetColumnWidth(0, 5000);
                sheet.SetColumnWidth(1, 5000);
                sheet.SetColumnWidth(2, 5000);
                sheet.SetColumnWidth(3, 5000);

                IRow headerRow = sheet.CreateRow(0);

                // handling header. 
                foreach (DataColumn column in table.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value 

                // handling value. 
                int rowIndex = 1;

                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);

                    foreach (DataColumn column in table.Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    }

                    rowIndex++;
                }

                workbook.Write(ms);
                ms.Flush();
                ms.Close();
                System.Diagnostics.Process.Start(filePath);
            }
            catch (System.Exception e)
            {
                if(ms != null)
                    ms.Close();
                MessageBox.Show(e.Message);
            }

        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            SetNeedLockPhoneNumFrm frm = new SetNeedLockPhoneNumFrm();
            frm.ShowDialog();
        }

        private void cbk8_CheckedChanged(object sender, EventArgs e)
        {
            if (cbk7.Checked)
            {
                cbk1.Checked = false;
                cbk2.Checked = false;
                cbk3.Checked = false;
                cbk4.Checked = false;
                cbk5.Checked = false;
                cbk6.Checked = false;
                //this.textBox4.Text = "2";
                //this.textBox4.Enabled = true;
            }
        }

        private void cbk1_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            if (cb.Checked)
            {
                cbk7.Checked = false;
                //this.textBox4.Text = "2";
                //this.textBox4.Enabled = false;
            }
        }

        private bool checkIsScanStop()
        {
            if (!this.m_IsScaning)
                return true;

            //if (m_ScanStopTime != null && DateTime.Now.CompareTo(m_ScanStopTime) > 0)
            //    return true;

            return false;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("号码规则");
            dt.Columns.Add("手机号码");
            dt.Columns.Add("预存");
            dt.Columns.Add("低消");
            dt.Columns.Add("锁定状态");


            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                DataRow newRow = dt.NewRow();
                for (int i = 0; i < 4; i++)
                {
                    newRow[i] = row.Cells[i].Value;
                }
                newRow[4] = row.Cells[5].Value;
                dt.Rows.Add(newRow);
            }

            MainFrm.RenderToExcel(dt);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("请先选择号码");
                return;
            }

            string[] item = (string[])this.dataGridView1.CurrentRow.Tag;
            bool isNeedLockNum = true;
            if (item[4] == "true")
            {
                if (DateTime.Parse(item[2]).AddMinutes(30) > DateTime.Now)
                    isNeedLockNum = false;
            }

            if (isNeedLockNum)
            {
                string[] temp_car = MainFrm.self.lockNum(item[0], item[1],item[6],item[7],item[8]);
                if (temp_car != null && temp_car[2] == "true")
                    MainFrm.self.showProductCar(temp_car[0], temp_car[1], item[1], item[8], item[9]);
                else
                {
                    MessageBox.Show("号码锁定失败！请重试！");
                }
            }
            else
            {
                MainFrm.self.showProductCar(item[3], item[5], item[1], item[8], item[9]);

            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            DataGridViewRow row = this.dataGridView1.CurrentRow;
            if (row == null)
                return;

            if (MessageBox.Show("确定删除选中的锁定号码吗？", "确认", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                MainFrm.self.deleteLockNum();
                this.refreshNewPhone();
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.refreshImageCode();
        }

        private int m_GetVerifyCodeIndex = -1;
        private string[] getVerifyCode()
        {
            lock (m_VerifyCodeList)
            {
                if (m_VerifyCodeList.Count > 0)
                {
                    string[] re = m_VerifyCodeList[m_VerifyCodeList.Count - 1];
                    m_VerifyCodeList.Remove(re);
                    return re;
                }
            }

            lock (m_AutoVerifyCodeList)
            {
                m_GetVerifyCodeIndex++;
                m_GetVerifyCodeIndex = m_GetVerifyCodeIndex % m_AutoVerifyCodeList.Count;
            }

            for (int i = m_GetVerifyCodeIndex; i < m_AutoVerifyCodeList.Count; i++)
            {
                List<string[]> list = m_AutoVerifyCodeList[i];
                lock (list)
                {
                    int length = list.Count;
                    if (length > 0)
                    {
                        string[] re = list[length - 1];
                        list.Remove(re);
                        return re;
                    }
                }
            }

            

            throw new ApplicationException("缺少验证码！");
        }

        private string urlEncod(string input)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = this.m_Encoding.GetBytes(input);
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }
            return sb.ToString().ToUpper();
        }

        private void txtVerifyCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btnSaveVCode_Click(null,null);
            }
        }

        private void btnSaveVCode_Click(object sender, EventArgs e)
        {
            if (this.txtVerifyCode.Text.Length != 4)
            {
                MessageBox.Show("输入的验证码错误！");
                return;
            }

            bool isAdd = false;
            lock (m_VerifyCodeList)
            {
                if (m_VerifyCodeList.Count < 100)
                {
                    m_VerifyCodeList.Add(new string[] { this.txtVerifyCode.Text, this.m_NewSessionId });
                    isAdd = true;
                }
            }

            this.lbVerifyCodeNum.Text = "当前可用验证码（" + m_VerifyCodeList .Count+ "）个";
            if (!isAdd)
            {
                MessageBox.Show("最多只能录入100个验证码！");
            }
            this.refreshImageCode();
        }

        private void txtVerifyCode_Enter(object sender, EventArgs e)
        {
            long t = DateTime.Now.Millisecond - this.m_LastRefreshImageTime;
            if (t > 1000 * 60 * 5)
            {
                this.refreshImageCode();
            }
        }

        private bool m_IsJingPinScaning = false;
        private string m_ScanJingPinType = "";
        private List<ManualResetEvent> m_JingPinSet = new List<ManualResetEvent>();
        private List<PhoneOrder> m_JingPinHisNumList = new List<PhoneOrder>();
        private List<int> m_LockOkNumList = new List<int>();
        private long m_JingPinScanCount = 0;
        private int m_JingPinScanLockThreadCount = 0;
        private object m_JingPinScanLockObject = new object();
        private bool m_IsJingPinLockStarted = false;
        private void button7_Click(object sender, EventArgs e)
        {
            m_IsJingPinScaning = !m_IsJingPinScaning;
            if (m_IsJingPinScaning)
            {
                m_ScanJingPinType = this.comboBox3.SelectedValue.ToString();
                int iThreadCount = int.Parse(this.textBox3.Text);

                m_JingPinScanLockThreadCount = 0;
                m_JingPinScanCount = 0;
                m_LockOkNumList.Clear();
                m_IsJingPinLockStarted = false;
                m_JingPinSet = new List<ManualResetEvent>();
                for (int i = 0; i < iThreadCount; i++)
                {
                    ManualResetEvent set = new ManualResetEvent(false);
                    m_JingPinSet.Add(set);
                    JingPinScanThread t = new JingPinScanThread(set);
                    Thread thread = new Thread(new ThreadStart(t.run));
                    thread.Name = "极品线程" + i;
                    thread.IsBackground = true;
                    thread.Start();
                }

                this.timer3.Enabled = true;
                this.button7.Text = "结束扫描";
                this.label13.Text = "第1轮扫描...";
                this.label13.Visible = true;
                this.comboBox3.Enabled = false;
                this.textBox3.Enabled = false;
            }
            else
            {
                foreach (ManualResetEvent set in m_JingPinSet)
                {
                    set.WaitOne();
                }

                this.timer3.Enabled = false;
                this.button7.Text = "开始扫描";
                this.label13.Visible = false;
                this.comboBox3.Enabled = true;
                this.textBox3.Enabled = true;
            }
        }

        public void scanJingPin(ManualResetEvent set)
        {
            try
            {
                string strTmp;
                List<PhoneOrder> tmpPagePhoneList;
                while (true)
                {
                    try
                    {
                        if (!m_IsJingPinScaning)
                            break;

                        strTmp = getJingPinPageStr();
                        tmpPagePhoneList = this.dealPagePhoneInfo(strTmp, "beautiful", m_ScanJingPinType);

                        if (tmpPagePhoneList.Count > 0)
                        {
                            //lock (m_JingPinScanLockObject)
                            //{
                            //    if (!m_IsJingPinLockStarted)
                            //    {
                            //        log.Error("扫描到极品号码报文：" + strTmp);
                            //        m_JingPinHisNumList = tmpPagePhoneList;
                            //        m_IsJingPinLockStarted = true;
                            //    }
                            //    m_JingPinScanLockThreadCount++;
                            //    if (m_JingPinScanLockThreadCount > 20)
                            //        break;

                            //    threadIndex = m_JingPinScanLockThreadCount % m_JingPinHisNumList.Count;
                            //    continue;
                            //}

                            for(int i= tmpPagePhoneList.Count; i > 0; )
                            {
                                PhoneOrder phone = tmpPagePhoneList[i-1];
                                string[] re = this.lockNum(phone.m_RuleParam, phone.m_Num, phone.m_PrestoreMoney, phone.m_BaseFeeMoney, "536");
                                if (re != null)
                                {
                                    i--;
                                }
                            }
                            
                        }


                        lock (m_JingPinScanLockObject)
                        {
                            m_JingPinScanCount++;
                        }
                        //Thread.Sleep(100);
                    }
                    catch (System.Exception e)
                    {
                        log.Debug("极品号码扫描出错：" + e.Message);
                    }
                }

            }
            finally
            {
                set.Set();
            }
        }


        private string getJingPinPageStr()
        {
            if (!this.m_IsJingPinScaning)
                return "";

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.NoDelay = true;
            try
            {

                string data = string.Format("scenseFlag={0}&region=536&continue_url=", m_ScanJingPinType);

                Uri uri = new Uri("http://www.sd.10086.cn/");
                socket.Connect(uri.Host, uri.Port);
                string strResult = "";
                string strSendInfo = "POST /emall/activity/queryFlashSaleNum.action?t=" +DateTime.Now.Millisecond+ " HTTP/1.1\r\n"
                                    + "Content-Type: application/x-www-form-urlencoded\r\n"
                                    + "Content-Length: " + data.Length + "\r\n"
                                    + "Connection: Keep-Alive\r\n"
                                    + "Host: www.sd.10086.cn\r\n\r\n"
                                    + data + "\r\n";
                socket.Send(this.m_Encoding.GetBytes(strSendInfo));
                strResult = this.getSocketReceiveText(socket, new string[] { "]}", "</html>" }, 1024 * 5);
                return strResult;
            }
            finally
            {
                socket.Close();
            }
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            this.label13.Text = string.Format("第{0}轮扫描...", m_JingPinScanCount) ;
        }
    }
}